<template>
	<ls-page title='优惠券'  :hidden="true"  :userIdentity='1' leftIcon='' :autoBack='false'>
		
		<view class="coupon-container">
			<!-- 选项卡start -->
			<view class="tabs-contianr filter-continar-box fixed" :class="{ 'fixed-bg': isFixed }">
			<!-- <view class="tabs-contianr filter-continar-box fixed" > -->
				<view class="nav-bd">
				<TabList :list="list1" v-model:activeIndex="activeIndex" @tabClick="handleTabClick" />
				</view>
				<view class="filter-continar "  >
					<zb-popover placement="bottom-start" :options="actions" ref="Popover1" @select="handleClick"
						class="item-popover">
						<view class="filter-continar">
							<view class="filter-title">
								{{sortName}}
							</view>
							<image class="filter-arrow"
								src="https://oss.jtmckj.com/h5-uniapp/blanKarea/coupon/filter-arrow.png" mode=""></image>
						</view>
					</zb-popover>
				</view>
			</view>
			<!-- 选项卡end -->
				<view class="coupon-container-main">
					<!-- 列表内容start -->
				<!-- 	<scroll-view class="main-scroll" @scrolltolower="scrollToLower" :scroll-y="true"
						lower-threshold="200"> -->
						<view class="main-scroll">
							
					
						<view :class="'container-main-discount ' + (couponState == '1' ? 'bac-y' : 'bac-f')"
							:data-item="v" @tap="onClickItem(v)" v-for="(v, k) in voucher" :key="k">
							<view :class="couponState == '1' ? 'discount-item' : 'discount-item discount-gay'">
								<view class="discount-item-main">
									<view class="item-main-left">
										<view class="main-left-top" v-if="v.TypeCodeName == '兑换券'"
											style="background: #ffe6b2">{{ v.TypeCodeName }}</view>
										<view class="main-left-top" v-if="v.TypeCodeName == '折扣券'"
											style="background: #ffccb2">{{ v.TypeCodeName }}</view>
										<view class="main-left-top" v-if="v.TypeCodeName == '优惠券'"
											style="background: #ffb2b2">{{ v.TypeCodeName }}</view>
										<view class="main-left-top" v-if="v.TypeCodeName == '免排队券'"
											style="background: #ffffb2;">免排券</view>
										<view v-else-if="v.TypeCodeName" class="main-left-top">{{ v.TypeCodeName }}
										</view>
										<!-- <view :class="couponState == '1' ? 'main-left-bottom' : 'main-left-bottom-type'">{{ v.TicketName }}</view> -->
										<image class="main-left-img" :src="v.attachment" v-if="v.attachment"/>
										<image class="main-left-img" src="https://oss.jtmckj.com/public/icon/defut-yhj.png" v-else/>
									</view>
									<view class="item-main-right">
										<view :class="couponState == '1' ? 'main-right-center' : 'main-right-center'"
											v-if="v.TypeCode == '3'">
											{{ v.TicketName }}
										</view>
										<view :class="couponState == '1' ? 'main-right-center' : 'main-right-center'"
											v-if="v.TypeCode == '1'">减{{ v.TicketAmt }}元</view>
										<view :class="couponState == '1' ? 'main-right-center' : 'main-right-center'"
											v-if="v.TypeCode == '2'">
											{{ Number(v.Discounts) }}折优惠
										</view>
										<view :class="couponState == '1' ? 'main-right-center' : 'main-right-center'"
											v-if="v.TypeCode == '4'">免排队一次</view>
										<view style="display: flex">
											<view :class="couponState == '1' ? 'main-right-top' : 'main-right-top'">
												有效期：{{ v.EndData ? v.EndData : '--' }}</view>
										</view>
										<view :class="couponState == '1' ? 'main-right-footer' : 'main-right-footer'"
											v-if="v.UseCondition == '1'">
											<!-- 1 桌台限制  2 会员限制 0 无限制 -->
											使用限制：每桌仅限使用{{ v.RoomUseNum }}张
										</view>
										<view :class="couponState == '1' ? 'main-right-footer' : 'main-right-footer'"
											v-if="v.UseCondition == '2'">
											<!-- 1 桌台限制  2 会员限制 0 无限制 -->
											使用限制：单次消费可用{{ v.MemberUseNum }}张
										</view>
										<view :class="couponState == '1' ? 'main-right-footer' : 'main-right-footer'"
											v-if="v.UseCondition == '0'">
											<!-- 1 桌台限制  2 会员限制 0 无限制 -->
											无使用限制
										</view>
									</view>
								</view>
								<view v-if="v.IsNew && couponState == '1'" class="discount-item-icon"></view>
								<view v-else-if="couponState == '2'" class="discount-item-icon-type">已使用</view>
								<view v-else-if="couponState == '3'" class="discount-item-icon-type">已过期</view>
							</view>
						</view>
							</view>
					<!-- </scroll-view> -->
					<!-- 列表内容end -->

				</view>

			<!-- </view> -->



		</view>

	</ls-page>
</template>

<script setup>
	import dayjs from 'dayjs';
	import { ref } from 'vue';
	import { onLoad, onUnload, onShow, onHide } from '@dcloudio/uni-app';
	import { HFiveAppObjProcess, HFiveMemberAppObjProcess, GetMinimsgTemplate } from '@/api/public.js'

	// -------------------------------------------------------初始化数据-----------------------------------------------------
	const shopInfo = uni.getStorageSync('shopInfo') //门店信息
	const userInfo = uni.getStorageSync('userInfo') //用户信息
	const cardInfo = uni.getStorageSync('cardInfo')
	console.log(cardInfo.code, 'cardInfo')
	// 响应式数据
	const activeIndex = ref(0);
	// const actions = [
	// 	{ text: '按分类' },
	// 	{ text: '按获得时间' },
	// 	{ text: '按过期时间' },
	// ];
	// const defutFitler = ref('综合排序')


	const sortShow = ref(false);
	const sortShowIni = ref(false);
	const couponList = ref([]); // 折扣券
	const discountList = ref([]); // 满减券
	const voucher = ref([]); // 商品券
	const isShow = ref(false);
	const canUsed = ref(true);
	const expired = ref(''); // 已过期
	const used = ref(''); // 已使用
	const notUsed = ref(''); // 未使用

	const list1 = ref([
		{ name: '未使用(0)' },
		{ name: '已使用(0)' },
		{ name: '已过期(0)' },
	]);
    const actions = [
    	{ text: '按分类' },
    	{ text: '按获得时间' },
    	{ text: '按过期时间' },
    ];
	
	const defutFitler = ref('综合排序')
	
	const active = ref(0); // 当前选中的 tab

	// 请求参数
	const postForm = ref({
		ticketState: '1',
		ticketName: '',
		MemberCarCode: cardInfo.code,
		pageSize: '10',
		page: '1'
	});
	console.log(postForm, 'postForm')
	const couponState = ref('1');
	const hasMore = ref(true); // 是否还有数据
	const sortName = ref('综合排序');
    const isFixed = ref(false)
	// -------------------------------------------------------初始化数据-----------------------------------------------------
	onShow((options) => {
		// 判断 TabBar 是否已初始化
		if (typeof getTabBar === 'function' && getTabBar()) {
			getTabBar().setData({
				selected: 1, // 设置选中 Tab 的索引
			});
		}
		
		postForm.value.MemberCarCode = uni.getStorageSync('cardInfo').code
			console.log(postForm.value.MemberCarCode, 'cardInfo')
			getCoupon(true)
	})
	
		onPageScroll(e => {
			console.log('kk9999999999999999999')
			console.log(e,'kk')
			if (e.scrollTop >=20) {
				isFixed.value = true
			} else {
			    isFixed.value = false
			}
		})

	// 更新访问量的函数
	const updateAccess = async () => {
		const params = {
			orgCode: uni.getStorageSync('ORG_CODE'),
			memberCode: app.global.userInfo.userCode,
			memberMobile: app.global.userInfo.mobile,
			unionId: app.global.userInfo.unionID,
			openId: app.global.userInfo.openId,
		};

		let loginLog;
		try {
			loginLog = await Api.Common.MiniProgramLoginLog.Do(params);
			console.log('Login log updated:', loginLog);
		} catch (error) {
			console.error('Failed to update login log:', error);
		}
	};

	// 点击事件处理
	const onClickItem = (item) => {
		// 前提条件：TypeCode兑换券且该券未使用
		if (item.TypeCode === '3' && postForm.value.ticketState === '1') {
			const sendForm = encodeURIComponent(JSON.stringify(item));
			console.log(item,'dadas')
			uni.navigateTo({
				url: `./detail?code=${item.Code}`,
			});
			// const targetUrl = `/detail?sendForm=${encodeURIComponent(sendForm)}`; // 确保对参数进行编码
			// window.location.href = targetUrl;
		} else {
			// 处理其他情况
			console.log('Item does not meet criteria');
		}
	};


	// 切换排序框显示状态
	const sortOpen = () => {
		sortShow.value = !sortShow.value;
	};


	// 排序功能
	const sortClass = (sortS) => {
		sortName.value = sortS;
		getCoupon(true, sortS);
	};

	// 获取优惠券数据
	   const getCoupon = async (flag, sortS) => {
	      if (flag) {
	        postForm.value.page = '1';
	        hasMore.value= true;
	      }
	
	      try {
	        const res = await HFiveMemberAppObjProcess({
	          functionName: 'GetMemberTicket_H5',
	          contentData: postForm.value
	        });
	        let points = res.result;
	
	        // 按照分类进行排序
	        if (sortName.value == '按分类') {
				console.log('fsdafsd')
	          let type1 = [];
	          let type2 = [];
	          let type3 = [];
	
	          points.forEach(e => {
	            if (e.TypeCode === '1') {
	              type1.push(e);
	            } else if (e.TypeCode === '2') {
	              type2.push(e);
	            } else if (e.TypeCode === '3') {
	              type3.push(e);
	            }
	          });
	
	          points = [];
	          points.push(...type3, ...type2, ...type1);
	        }  else if (sortName.value == '按获得时间') {
		     points.sort((a, b) => dayjs(b.CrDate).valueOf() - dayjs(a.CrDate).valueOf());
		   }
		   // 按过期时间排序
		   else if (sortName.value == '按过期时间') {
		     points.sort((a, b) => dayjs(a.EndData).valueOf() - dayjs(b.EndData).valueOf());
		   }
		   
	        // 格式化过期时间
	        points.forEach(item => {
	          item.EndData = dayjs(item.EndData).format('YYYY-MM-DD HH:mm:ss');
	        });
	          
			console.log(points,'points-----------')
	        // 更新响应式数据
	        voucher.value= points;
	    		// 设置标签列表
	    		list1.value = [
	    			{ name: `未使用(${res.notUsed})` },
	    			{ name: `已使用(${res.used})` },
	    			{ name: `已过期(${res.expired})` }
	    		];
				
	        sortShow.value = false;
	      } catch (error) {
	        console.error('获取优惠券失败:', error);
	      }
	    };
	

	// 上拉加载更多
	const scrollToLower = () => {
	
	};
	
	onReachBottom(() => {
		console.log('上拉加载更多')
		if (!hasMore.value) return;
		postForm.value.page++;
		
		HFiveMemberAppObjProcess({
			functionName: 'GetMemberTicket_H5',
			contentData: postForm.value
		}).then(res => {
			res.result.forEach(item => {
				item.EndData = dayjs(item.EndData).format('YYYY-MM-DD HH:mm:ss');
			});
		
			hasMore.value = res.result.length > 0;
			voucher.value = [...voucher.value, ...res.result];
		});
	});



	const handleClick = (v) => {
		sortName.value = v.text
		sortClass(v.text)
	}

	const toDeatil = () => {
		uni.navigateTo({
			url: './detail'
		})
	}

	const handleTabClick = (e) => {
		voucher.value = [] //清空当前优惠券
		if (e.index === 0) {
			couponState.value = '1'
			postForm.value.ticketState = '1'
		} else if (e.index === 1) {
			couponState.value = '2'
			postForm.value.ticketState = '2'
		} else if (e.index === 2) {
			couponState.value = '3'
			postForm.value.ticketState = '3'
		}
		getCoupon(true);
	};
	
</script>

<style lang="less" scoped>
	.tabs-contianr {
		// background: var(--maincolor);
		// padding: 0 40rpx 0 47rpx;
		// border-bottom: 1rpx solid var(--maincolorbd);
	}
	.nav-bd {
		padding: 0 40rpx 0 47rpx;
		 border-bottom: 1rpx solid var(--maincolorbd);
	}

	.filter-continar {
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: flex-end;
	}

	.filter-title {
		margin-right: 12rpx;
		font-weight: 500;
		font-size: 32rpx;
		color: var(--maincolorf1);
	}
		
	.filter-continar-box.fixed {
		  position: fixed;
		  z-index: 9999;
		  top: 0;
		  left: 0;
		  right: 0;
		  padding-right: 24rpx;
		  // background: #ffffff;
		  // background: #f2f2f2;
	}
	.fixed-bg {
		background: #fff !important;
	}

	.filter-arrow {
		width: 18rpx;
		height: 12rpx;
	}

	.coupon-container {
		// width: 100%;
		// height: 100%;
		// box-sizing: border-box;
		// padding-bottom: 100rpx;
       // padding-top: 91px;
       // background-image: url(https://oss.jtmckj.com/wmp/qnjg/center/i_center_bg.png);
	     // background-size: cover;
		background-size: 100% 100%;
		min-height: 100vh;
		padding-bottom: 160rpx;
	     // background-position: 20px 30px; /* 向右偏移20px'，向下偏移30px */
		.coupon-container-main {
			padding: 20rpx 24rpx;
			// height: 84%;
            padding-top: 190rpx;
			.main-sort {
				font-size: 30rpx;
				position: relative;
				display: flex;
				justify-content: flex-end;
				margin-bottom: 20rpx;

				.sort-title {
					width: 200rpx;
					display: flex;
					align-items: center;
					justify-content: center;

					/* text-align: center;*/
					image {
						width: 20rpx;
						height: auto;
						margin-left: 10rpx;
					}
				}

				.mainopen image {
					animation: Mopen 0.8s;
					animation-fill-mode: forwards;
				}

				.mainclose image {
					animation: Mclose 0.8s;
				}

				.sortopen {
					animation: Sopen 0.5s;
					animation-fill-mode: forwards;
				}

				.sortclose {
					animation: Sclose 0.5s;
				}

				.sort-list {
					z-index: 99;
					background-color: var(--maincolor);
					width: 200rpx;
					text-align: center;
					padding: 0 20rpx;
					box-sizing: border-box;
					border-radius: 10rpx;
					position: absolute;
					top: 60rpx;
					overflow: hidden;
					height: 0;

					view {
						padding: 30rpx 0;
						border-bottom: 2rpx solid var(--maincolorbd);
					}

					@keyframes Sopen {
						0% {
							height: 0;
						}

						100% {
							height: 306rpx;
						}
					}

					@keyframes Sclose {
						0% {
							height: 306rpx;
						}

						100% {
							height: 0;
						}
					}

					@keyframes Mopen {
						0% {
							transform: rotate(0);
						}

						100% {
							transform: rotate(180deg);
						}
					}

					@keyframes Mclose {
						0% {
							transform: rotate(180deg);
						}

						100% {
							transform: rotate(0);
						}
					}
				}
			}

			.main-scroll {
				overflow: scroll;
				height: 100%;

				/* 满减券*/
				/* .container-main-discount{  */
				/* }*/
				/* 折扣券*/
				.container-main-coupon {}

				/* 商品券*/
				.container-main-voucher {}

				.bac-y {
					/* background: #FFE8A7; */
				}

				.bac-f {
					background: #ffffff;
				}

				.container-main-discount {
					margin-bottom: 20rpx;
					border-radius: 16rpx;

					.discount-item {
						position: relative;
						display: flex;
						/* align-items: center;*/
						justify-content: space-between;
						/* background: #FFFCF2;*/
						border-radius: 16rpx;
						background-image: url('https://oss.jtmckj.com/wmp/qnjg/coupon/i_card_dui.png');
						background-size: 100% 100%;
						/* background-repeat: no-repeat;*/
						/* background-position: center;*/

						.discount-item-main {
							position: relative;
							display: flex;
							align-items: center;
							padding: 26rpx 0 26rpx 0rpx;

							.item-main-left {
								width: 180rpx;
								text-align: center;
								margin-right: 20rpx;

								.main-left-top {
									position: absolute;
									left: 0;
									top: 0;
									z-index: 999;
									width: 80rpx;
									height: 32rpx;
									border-radius: 16rpx 0rpx 16rpx 0rpx;
									font-family: PingFang SC;
									font-weight: 500;
									font-size: 20rpx;
									color: var(--maincolorf1);
								}

								.main-left-bottom {
									font-family: PingFang SC;
									font-weight: 600;
									font-size: 28rpx;
									color: var(--maincolorf5);
									line-height: 32rpx;
									max-height: 58rpx;
									overflow: hidden;
									/* 必须有 */
									display: -webkit-box;
									/* 必须有 */
									-webkit-line-clamp: 2;
									/* 行数 */
									-webkit-box-orient: vertical;
									/* 必须有 */
								}
								.main-left-img{
									width: 140rpx;
									height: 140rpx;
									border-radius: 12rpx;
								}
								
							}

							.item-main-right {
								.main-right-top {
									display: flex;
									align-items: center;
									padding: 0 15rpx;
									height: 36rpx;
									background: var(--mainbaccolor17);
									border-radius: 4rpx;
									font-family: PingFang SC;
									font-weight: 500;
									font-size: 24rpx;
									color: var(--maincolorf3);
									line-height: 24rpx;
									white-space: nowrap;
								}

								.main-right-center {
									font-family: PingFang SC;
									font-weight: bold;
									font-size: 32rpx;
									color: var(--maincolorf1);
									line-height: 40rpx;
									padding: 0rpx 0 19rpx 0;
								}

								.main-right-footer {
									margin-top: 19rpx;
									font-family: PingFang SC;
									font-weight: 500;
									font-size: 24rpx;
									color: var(--maincolorf4);
									line-height: 24rpx;
								}
							}
						}

						.discount-item-icon {
							width: 48rpx;
							height: 32rpx;
							background-image: url('https://oss.jtmckj.com/wmp/images/center/coupon/i_icon_new.png');
							background-size: 100% auto;
							background-repeat: no-repeat;
						}
					}

					/* 已使用状态*/
					.discount-gay {
						background-image: url('https://oss.jtmckj.com/wmp/qnjg/coupon/i_card_dui-gay.png');
						background-size: 100% 100%;

						.discount-item-main {
							// padding-left: 20rpx;
						}

						.item-main-right {
							// padding-left: 20rpx;
						}

						.main-right-center {
							width: 396rpx;
							color: var(--maincolorf2) !important;
						}

						.main-left-top {
							background: var(--maincolorf18) !important;
							color: var(--maincolorf2) !important;
						}

						.main-right-top {
							background: var(--maincolorf17) !important;
							color: var(--maincolorf4) !important;
							line-height: 36rpx !important;
						}
					}

					.canNotUse {
						/* filter: grayscale(100%);*/
						display: flex;
						/* align-items: center;*/
						border-radius: 16rpx;
						justify-content: space-between;

						.discount-item-main {
							display: flex;
							align-items: center;
							padding: 27rpx 0 23rpx 0rpx;

							.item-main-left {
								width: 180rpx;
								text-align: center;
								margin-right: 20rpx;

								.main-left-top {
									position: absolute;
									top: 0;
									left: 0;
									width: 80rpx;
									height: 32rpx;
									border-radius: 16rpx 0rpx 16rpx 0rpx;
									font-family: PingFang SC;
									font-weight: 500;
									font-size: 20rpx;
									color: var(--maincolorf4);
								}

								.main-left-bottom {
									font-family: PingFang SC;
									font-weight: bold;
									font-size: 28rpx;
									color: var(--maincolorf5);
									line-height: 28rpx;
									max-height: 58rpx;
									overflow: hidden;
									/* 必须有 */
									display: -webkit-box;
									/* 必须有 */
									-webkit-line-clamp: 2;
									/* 行数 */
									-webkit-box-orient: vertical;
									/* 必须有 */
								}
							}

							.item-main-right {
								.main-right-top {
									font-family: PingFang SC;
									font-weight: 500;
									font-size: 24rpx;
									color: var(--maincolorf4);
									line-height: 24rpx;
								}

								.main-right-center {
									font-family: PingFang SC;
									font-weight: bold;
									font-size: 32rpx;
									color: var(--maincolorf1);
									line-height: 32rpx;
									padding: 18rpx 0 16rpx 0;
								}

								.main-right-footer {
									font-family: PingFang SC;
									font-weight: 500;
									font-size: 24rpx;
									color: var(--maincolorf19);
									line-height: 24rpx;
								}
							}
						}

						.discount-item-icon {
							width: 48rpx;
							height: 32rpx;
							background-image: url('https://oss.jtmckj.com/wmp/images/center/coupon/i_icon_new.png');
							background-size: 100% auto;
							background-repeat: no-repeat;
						}
					}
				}
			}
		}

		.main-left-top-type {
			font-family: PingFang SC;
			font-weight: 600;
			font-size: 28rpx;
			color: var(--maincolorf4);
			line-height: 28rpx;
			padding-bottom: 15rpx;
		}

		.main-left-bottom-type {
			font-family: PingFang SC;
			font-weight: 600;
			font-size: 28rpx;
			color: var(--maincolorf2);
			line-height: 28rpx;
			max-height: 58rpx;
			overflow: hidden;
			/* 必须有 */
			display: -webkit-box;
			/* 必须有 */
			-webkit-line-clamp: 2;
			/* 行数 */
			-webkit-box-orient: vertical;
			/* 必须有 */
		}

		.main-right-top-type {
			font-family: PingFang SC;
			font-weight: 500;
			font-size: 24rpx;
			color: var(--maincolorf4);
			line-height: 24rpx;
		}

		.main-right-center-type {
			font-family: PingFang SC;
			font-weight: bold;
			font-size: 32rpx;
			color: var(--maincolorf2);
			line-height: 32rpx;
			padding: 18rpx 0 16rpx 0;
		}

		.main-right-footer-type {
			font-family: PingFang SC;
			font-weight: 500;
			font-size: 24rpx;
			color: var(--maincolorf4);
			line-height: 24rpx;
		}

		.discount-item-icon-type {
			position: absolute;
			right: 0;
			width: 120rpx;
			height: 40rpx;
			line-height: 40rpx;
			text-align: center;
			background: var(--maincolorf18);
			border-radius: 0rpx 16rpx 0rpx 16rpx;
			font-family: PingFang SC;
			font-weight: 500;
			font-size: 26rpx;
			color: var(--maincolor);
		}
	}
</style>